from flask import Blueprint, render_template, request, redirect, url_for, session, flash, jsonify, make_response
from models import UserModel, CardModel, db, TradeModel, DepositModel
from sqlalchemy import or_, func
import csv
from io import StringIO
import random
from datetime import datetime

admin_bp = Blueprint('admin', __name__, url_prefix='/admin')


def generate_card_id():
    """生成唯一的16位银行卡号"""
    prefix = "6217"
    for _ in range(5):  # 尝试5次
        # 生成12位随机数字
        random_part = ''.join([str(random.randint(0, 9)) for _ in range(12)])
        card_id = prefix + random_part

        # 检查是否已存在
        if not CardModel.query.get(card_id):
            return card_id
    return None  # 如果尝试多次都失败


@admin_bp.route('/adminmain')
def adminmain():
    """管理员主面板"""
    if not session.get('is_admin'):
        flash('无权访问管理员界面', 'error')
        return redirect(url_for('auth.login'))
    return render_template('adminmain.html')


@admin_bp.route('/admin_clientmanage', methods=['GET'])
def admin_clientmanage():
    if not session.get('is_admin'):
        flash('无权访问管理员界面', 'error')
        return redirect(url_for('auth.login'))

    # 获取搜索参数
    customer_id = request.args.get('customerId')
    id_card = request.args.get('idCard')

    # 构建查询
    query = UserModel.query

    if customer_id:
        query = query.filter(UserModel.customerID == customer_id)
    if id_card:
        query = query.filter(UserModel.PID.like(f'%{id_card}%'))

    # 分页处理
    page = request.args.get('page', 1, type=int)
    per_page = 10
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)
    customers = pagination.items

    return render_template('admin_main_clientmanage.html',
                           customers=customers,
                           pagination=pagination,
                           customerIdSearch=customer_id or '',
                           idCardSearch=id_card or '')


@admin_bp.route('/add_customer', methods=['POST'])
def add_customer():
    data = request.json
    # 检查身份证号是否已存在
    if UserModel.query.filter_by(PID=data['idCard']).first():
        return jsonify({'success': False, 'message': '身份证号已存在'}), 400

    # 创建新客户
    new_customer = UserModel(
        customerName=data['name'],
        PID=data['idCard'],
        telephone=data['phone'],
        address=data['address']
    )

    try:
        db.session.add(new_customer)
        db.session.flush()  # 获取自增ID

        # 生成银行卡号
        card_id = generate_card_id()
        if not card_id:
            return jsonify({'success': False, 'message': '生成银行卡号失败'}), 500

        # 创建默认银行卡
        new_card = CardModel(
            cardID=card_id,
            curID='RMB',
            savingID=1,  # 活期存款
            openDate=datetime.now(),
            openMoney=1.00,
            balance=1.00,
            passwd='888888',
            IsReportLoss='否',
            customerID=new_customer.customerID
        )
        db.session.add(new_card)
        db.session.commit()

        return jsonify({
            'success': True,
            'message': '客户添加成功',
            'id': new_customer.customerID
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'添加失败: {str(e)}'}), 500


@admin_bp.route('/update_customer/<int:customer_id>', methods=['PUT'])
def update_customer(customer_id):
    customer = UserModel.query.get_or_404(customer_id)
    data = request.json

    # 检查身份证号是否已被其他客户使用
    if data['idCard'] != customer.PID and UserModel.query.filter_by(PID=data['idCard']).first():
        return jsonify({'success': False, 'message': '身份证号已被其他客户使用'}), 400

    try:
        customer.customerName = data['name']
        customer.PID = data['idCard']
        customer.telephone = data['phone']
        customer.address = data['address']
        db.session.commit()
        return jsonify({'success': True, 'message': '客户信息更新成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'更新失败: {str(e)}'}), 500


@admin_bp.route('/delete_customer/<int:customer_id>', methods=['DELETE'])
def delete_customer(customer_id):
    customer = UserModel.query.get_or_404(customer_id)

    try:
        # 先删除关联的银行卡
        CardModel.query.filter_by(customerID=customer_id).delete()
        db.session.delete(customer)
        db.session.commit()
        return jsonify({'success': True, 'message': '客户删除成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'删除失败: {str(e)}'}), 500


@admin_bp.route('/export_customers_csv')
def export_customers_csv():
    if not session.get('is_admin'):
        return redirect(url_for('auth.login'))

    # 获取查询参数
    customer_id = request.args.get('customerId')
    id_card = request.args.get('idCard')

    query = UserModel.query

    if customer_id:
        query = query.filter(UserModel.customerID == customer_id)
    if id_card:
        query = query.filter(UserModel.PID.like(f'%{id_card}%'))

    customers = query.all()

    # 创建CSV文件
    si = StringIO()
    cw = csv.writer(si)
    cw.writerow(['客户编号', '客户姓名', '身份证号', '联系电话', '联系地址'])

    for customer in customers:
        cw.writerow([
            customer.customerID,
            customer.customerName,
            customer.PID,
            customer.telephone,
            customer.address
        ])

    # 构建响应
    output = si.getvalue()
    response = make_response(output)
    response.headers['Content-Type'] = 'text/csv; charset=utf-8'
    response.headers['Content-Disposition'] = 'attachment; filename=customers.csv'
    return response


@admin_bp.route('/get_customer/<int:customer_id>')
def get_customer(customer_id):
    if not session.get('is_admin'):
        return jsonify({'error': 'Unauthorized'}), 401

    try:
        customer = UserModel.query.get_or_404(customer_id)

        # 获取关联的银行卡
        cards = CardModel.query.filter_by(customerID=customer_id).all()

        # 获取交易记录（所有银行卡）
        card_ids = [card.cardID for card in cards]
        recent_transactions = []
        if card_ids:
            # 修复查询链式调用
            recent_transactions = TradeModel.query.filter(
                TradeModel.cardID.in_(card_ids)
            ).order_by(TradeModel.tradeDate.desc()).limit(5).all()

        return jsonify({
            'customer': {
                'id': customer.customerID,
                'name': customer.customerName,
                'idCard': customer.PID,
                'phone': customer.telephone,
                'address': customer.address
            },
            'cards': [{
                'cardID': card.cardID,
                'currency': card.curID,
                'balance': float(card.balance) if card.balance else 0,
                'status': '正常' if card.IsReportLoss == '否' else '挂失',
                'openDate': card.openDate.strftime('%Y-%m-%d %H:%M') if card.openDate else None
            } for card in cards],
            'recentTransactions': [{
                'date': transaction.tradeDate.strftime('%Y-%m-%d %H:%M') if transaction.tradeDate else None,
                'type': transaction.tradeType,
                'amount': float(transaction.tradeMoney) if transaction.tradeMoney else 0,
                'remark': transaction.remark
            } for transaction in recent_transactions]
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500